<template>
  <div class="material-group-container">
    <div class="header-section">
      <div class="action-buttons">
        <el-button type="danger" size="default" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        :data="materialGroupList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="materialcode" label="编码" width="150">
        </el-table-column>
        <el-table-column prop="materialname" label="名称" width="180">
        </el-table-column>
        <el-table-column prop="materialtypeName" label="类型" width="120">
        </el-table-column>
        <el-table-column prop="processrouteName" label="默认工艺路线" width="150" />
        <el-table-column prop="materialdescription" label="描述" />
        <el-table-column prop="createName" label="创建人" width="100">
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" >
          <template #default="scope">
            {{ scope.row.createTime ? moment(scope.row.createTime).format("yyyy-MM-DD") : '' }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="更新时间" width="180">
          <template #default="scope">
            {{ scope.row.updateTime ? moment(scope.row.updateTime).format("yyyy-MM-DD") : '' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="danger" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-section">
        <div class="total-count">共 {{ pagination.total }} 条数据</div>
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, jumper, sizes"
          :total="pagination.total"
        />
      </div>
    </div>

    <!-- 添加/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        label-width="100px"
      >
        <el-form-item label="物料编码" prop="materialcode">
          <el-input v-model="formData.materialcode" placeholder="请输入物料编码" />
        </el-form-item>
        <el-form-item label="物料名称" prop="materialname">
          <el-input v-model="formData.materialname" placeholder="请输入物料名称" />
        </el-form-item>
        <el-form-item label="物料类型" prop="materialtypeid">
          <el-select v-model="formData.materialtypeid" placeholder="请选择物料类型">
            <el-option
              v-for="item in materialTypes"
              :label="item.materialtypeName"
              :value="item.materialtypeid"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="默认工艺路线" prop="id" v-show="formData.materialtypeid === 1 || formData.materialtypeid === 3">
          <el-select v-model="formData.id" placeholder="请选择默认工艺路线">
            <el-option
              v-for="item in processRoutes"
              :label="item.processrouteName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="物料描述" prop="materialdescription">
          <el-input
            v-model="formData.materialdescription"
            placeholder="请输入物料描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { APIs } from '../../Http/http'
import moment from 'moment'

// 表格数据
const materialGroupList = ref<any[]>([])
const searchKeyword = ref('')


// 分页数据
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0
})

// 弹窗数据
const dialogVisible = ref(false)
const dialogTitle = ref('添加物料群组')
const formRef = ref()
const formData = reactive({
  "id": 0,
  "materialcode": "",
  "materialname": "",
  "materialtypeid": null,
  "materialdescription": "",
})

// 选中的行
const selectedRows = ref<any[]>([])

// 下拉框数据
const materialTypes = ref<any[]>([])
const processRoutes = ref<any[]>([])

// 获取物料类型列表
const getMaterialTypes = () => {
  APIs.get('/api/Read/GetAllMaterialTypes').then(res => {
    materialTypes.value = res.data.data
  })
}

// 获取工艺路线列表
const getProcessRoutes = () => {
  APIs.get('/api/Read/GetAllProcessroutes')
    .then(res => {
      processRoutes.value = res.data.data
    })
}

// 获取物料群组列表
const getMaterialGroupList = () => {
  const params = {
    Pageindex: pagination.pageIndex,
    PageSize: pagination.pageSize,
    Keyword: searchKeyword.value,
  }
  APIs.get('/api/Read/GetMaterialGroupLivst', { params })
    .then(res => {
      materialGroupList.value = res.data.data.data
      pagination.total = res.data.data.totalCount
    })
}



// 添加物料群组
const handleAdd = () => {
  dialogTitle.value = '添加物料群组'
  resetForm()
  dialogVisible.value = true
}

// 编辑物料群组
const handleEdit = (row: any) => {
  dialogTitle.value = '修改物料群组'
  // 复制数据到表单
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleDelete = async (row: any) => {
   {
    await ElMessageBox.confirm('确定要删除这条数据吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
  await APIs.post('/api/Write/DeleteMaterialGroup', row)
    ElMessage.success('删除成功')
    getMaterialGroupList()
  }
}




// 表单提交
const handleSubmit = () => {
  formRef.value.validate((valid: boolean) => {
    if (valid) {
      const isAdd = dialogTitle.value === '添加物料群组'
      const apiUrl = isAdd ? '/api/Write/AddMaterialGroup' : '/api/Write/UpdateMaterialGroup'
      console.log(formData)
      APIs.post(apiUrl, formData)
        .then(() => {
          ElMessage.success(isAdd ? '添加成功' : '修改成功')
          dialogVisible.value = false
          getMaterialGroupList()
        })
    }
  })
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  Object.assign(formData, {
    id: 0,
    materialcode: '',
    materialname: '',
    materialtypeid: null,
    materialdescription: '',
    createtime: ''
  })
}

// 监听分页变化
watch(
  () => [pagination.pageIndex, pagination.pageSize],
  () => {
    getMaterialGroupList()
  },
  { deep: true }
)

// 初始化
onMounted(() => {
  getMaterialTypes()
  getProcessRoutes()
  getMaterialGroupList()
})
</script>

<style scoped>
.material-group-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 15px;
  background-color: #e8ebf1;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.search-tools {
  display: flex;
  align-items: center;
  gap: 5px;
}

.table-section {
  margin-bottom: 20px;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
}

.pagination-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

.total-count {
  color: #606266;
  font-size: 14px;
}

.column-header-with-search {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-icon {
  cursor: pointer;
  font-size: 14px;
}

.column-search {
  margin-top: 5px;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>